namespace HZY.Framework.Repository.EntityFramework.Interceptor;

/// <summary>
/// 默认数据字典映射拦截器
/// </summary>
public class DefaultDataDictionaryMappingIntercept : IDataDictionaryMappingIntercept
{
    public DictInfo HandlerData(DictInfo dictInfo, IUnitOfWork unitOfWork)
    {
        var tableName = dictInfo.DictAttribute.TableName;
        var codeName = dictInfo.DictAttribute.CodeName;
        var textName = dictInfo.DictAttribute.TextName;
        var valueList = dictInfo.Data.Keys.ToList();

        var codeInStr = new List<string>();
        var par = new Dictionary<string, object>();
        for (var i = 0; i < valueList.Count; i++)
        {
            var item = valueList[i];
            var key = "@" + codeName + i;
            codeInStr.Add(key);
            par[codeName + i] = item;
        }

        var sql =
            $" SELECT {codeName},{textName} FROM {tableName} WHERE {codeName} IN ({string.Join(',', codeInStr)})";

        var list = unitOfWork.FreeSqlOrm?.Ado.Query<Dictionary<string, object?>>(sql, par);

        if (list is null)
        {
            return dictInfo;
        }

        foreach (var item in list)
        {
            var codeValue = item[codeName];
            if (codeValue is null)
            {
                continue;
            }

            dictInfo.Data[codeValue] = item[textName];
        }

        return dictInfo;
    }
}